<template>
  <div>
    <crumbs secondTitle="商品管理" thirdTitle="商品添加"> </crumbs>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 警告框 -->
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      ></el-alert>
      <!-- 步骤条 -->
      <el-steps
        :space="200"
        :active="activeIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tap 标签页 -->
      <el-form
        :model="addForm"
        ref="addFormRef"
        :rules="addFormRules"
        label-width="100px"
        label-position="top"
        @close="closePage"
      >
        <el-tabs
          v-model="activeIndex"
          :tab-position="'left'"
          :before-leave="beforeTableLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat"
              ><el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cateProps"
                checkStrictly
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 渲染表单的 item 的项目 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTableList"
              :key="item.attr_id"
            >
              <!-- 复选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="item"
                  :key="index"
                  v-for="(item, index) in item.attr_vals"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :labl="item.attr_name"
              v-for="item in onlyTableList"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 图片上传 -->
            <!-- action 是指图片上传到的后台 API 地址 -->
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headersObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器组件  -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <!-- 添加商品的按钮 -->
            <el-button type="primary" class="btnAdd" @click="add"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
      <img :src="previewPath" class="previewImg" />
    </el-dialog>
  </div>
</template>
<script>
import _ from 'lodash'
import { getGoodsList, toObtainList, addGoods } from '@/api/add'
import config from '@/config'
import { storageGet } from '@/storage'
export default {
  data() {
    return {
      // 步骤条默认项 方便存入数据库
      // tap 标签页 v-model
      activeIndex: '0',
      // 添加商品的表单数据对象
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 商品分类的所属数组
        goods_cat: [],
        // 图片的数组
        pics: [],
        // 商品的详情介绍
        goods_introduce: '',
        attrs: []
      },
      // 添加商品的表单验证队则
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          {
            required: true,
            message: '请选择商品分类',
            trigger: 'blur'
          }
        ]
      },
      // 商品列表
      cateList: [],
      // 级联显示的规则
      cateProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 默认为 many
      sel: 'many',
      only: 'only',
      // many 获取的动态数据
      manyTableList: [],
      // only 获取的静态数据
      onlyTableList: [],
      // 上传图片的 URL 地址
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 图片上传组件的 headersObj
      headersObj: { Authorization: storageGet(config.SignName) },
      // 预览的图片路径
      previewPath: '',
      // 图片预览对话框
      previewVisible: false
    }
  },
  methods: {
    async getAddGoods() {
      const res = await getGoodsList()
      if (res.meta.status === 200) {
        // this.$message.success('获取商品数据成功')
        this.cateList = res.data
      }
    },
    handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    // tap 页 检测标签的切换 执行上一个页面钩子函数
    // activeNAme 是即将离开的页面 name ：0
    // oldActiveName 是即将进入的页面 name : 1
    beforeTableLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类的三级类型')
        return false
      }
    },
    async tabClicked() {
      if (this.activeIndex === '1') {
        // debugger
        const res = await toObtainList(this.cateId, this.sel)
        if (res.meta.status === 200) {
          // this.$message.success('获取数据成功')
          res.data.forEach(item => {
            item.attr_vals =
              item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
          })
          this.manyTableList = res.data
        }
      } else if (this.activeIndex === '2') {
        const res = await toObtainList(this.cateId, this.only)
        if (res.meta.status === 200) {
          // this.$message.success('获取静态参数成功')
          this.onlyTableList = res.data
        }
      }
    },
    // 处理图片预览的效果
    handlePreview(file) {
      this.previewPath = file.response.data.url
      this.previewVisible = true
    },
    // 处理图片移除的效果
    handleRemove(file) {
      // 1.获取将要删除图片的临时路径
      const filePath = file.response.data.tmp_path
      // 2.从 pics 数组中，找到这个图片的对应的索引值
      const index = this.addForm.pics.findIndex(item => item.pic === filePath)
      // 3.调用数组的 splice 方法，把图片信息对象，从 pics 数组中移除
      this.addForm.pics.splice(index, 1)
    },
    // 表单重
    closePage() {
      this.$refs.addFormRef.resetFields()
    },
    // 监听图片上传成功的事件
    handleSuccess(response) {
      // 1.拼接得到一个图片信息对象
      const picInfo = { pic: response.data.tmp_path }
      // 2.将图片信息对象 push 到 pics
      this.addForm.pics.push(picInfo)
    },
    // 添加按钮
    add() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写必填的表单项')
        }
        // 执行添加的业务
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        // 处理attrs数组，数组中需要包含商品的动态参数和静态属性
        // 将 manyTableList（动态参数）处理添加到attrs
        this.manyTableList.forEach(item => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          })
        })
        // 将 onlyTableList（静态属性）处理添加到attrs
        this.onlyTableList.forEach(item => {
          form.attrs.push({ attr_id: item.attr_id, attr_value: item.attr_vals })
        })
        form.attrs = this.addForm.attrs
        const res = await addGoods(form)
        if (res.meta.status === 201) {
          this.$message.success('添加商品成功')
          this.$router.push('/goods')
        }
      })
    }
  },
  mounted() {
    this.getAddGoods()
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  }
}
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.previewImg {
  width: 100%;
}

.btnAdd {
  margin-top: 15px;
}
</style>
